/******************************************************************************/
/* [[--]]                                                                     */
/*          ::::::::::::::::                                                  */
/*       :::::::::::::########:       Property of FlexyCore.                  */
/*     :::::::::::::############:                                             */
/*    :::::::::::..##############:    Unauthorized reproduction and/or        */
/*   ::::::::::...################:   distribution is strictly prohibited.    */
/*  :::::::::.....################.:                                          */
/*  :::::::::......##############..:  This product is protected under         */
/*  ::::::::........############...:  copyright law                           */
/*  ::::::::..........########.....:                                          */
/*   ::::::::.....................:   (c) Copyright 2008-2009, FlexyCore SAS. */
/*    ::::::::...................:                                            */
/*     ::::::::.................:     All rights reserved.                    */
/*       :::::::::............:                                               */
/*          ::::::::::::::::                                                  */
/* [[++]]                                                                     */
/******************************************************************************/

package com.flexycore.iphoneapps.weather;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;

import com.flexycore.iphone.coregraphics.CGRect;
import com.flexycore.iphone.uikit.NSIndexPath;
import com.flexycore.iphone.uikit.UIAlertView;
import com.flexycore.iphone.uikit.UITableView;
import com.flexycore.iphone.uikit.UITableViewCell;
import com.flexycore.iphone.uikit.UITableViewController;
import com.flexycore.iphone.uikit.UITableViewStyle;

public class WeatherView extends UITableViewController {
	// Data to map JSON key to UI name
	private WeatherData[] weatherData = {
			new WeatherData("stationName", "Station"),
			new WeatherData("temperature", "Temperature"),
			new WeatherData("humidity", "Humidity"),
			new WeatherData("windSpeed", "Wind Speed"),
			new WeatherData("dewPoint", "Dew Point"),
			new WeatherData("clouds", "Clouds") };

	public WeatherView(double latitude, double longitude) {
		initWithStyle(UITableViewStyle.UITableViewStylePlain);
		
		InputStreamReader isr = null;
		
		try {
			// Open the URL
			try {
				URL url;

				url = new URL(
						"http://ws.geonames.org/findNearByWeatherJSON?lat=" + latitude + "&lng=" + longitude);

				URLConnection conn = url.openConnection();
				conn.setDoInput(true);
				conn.setDoOutput(false);
				conn.setUseCaches(false);
				isr = new InputStreamReader(conn.getInputStream(), "UTF8");

			} 
			catch (IOException e)
			{
				// If an exception occurred during networking stuff, display an error alert
				new UIAlertView().initWithTitleMessageDelegateCancelButtonTitleOtherButtonTitles(
								"Weather", "Cannot load weather from Web", null, "OK").show();
			}
			
			// Parse the result as a JSON stream
			Map<String, Object> json = (Map<String, Object>) JSONValue
					.parse(isr);
			
			// Get the object containing data
			Map<String, Object> fields = (Map<String, Object>) json
					.get("weatherObservation");
			
			// Set values according to the JSON key
			for (int i = 0; i < weatherData.length; i++) {
				Object o = fields.get(weatherData[i].getJsonName());
				String s;
				if ( o != null )
				{
					if (o instanceof String)
						s = (String) o;
					else
						s = o.toString();

					weatherData[i].setValueText(s);
				}
			}
			// All values have a default text set to "N/A"
			// So, if an error occurred, all unset value will be displayed with "N/A"
		} catch (MalformedURLException e1) {
		} catch (IOException e) {
		} catch (ParseException e) {
		}

		setTitle("Nearest Weather Station");
	}

	public void loadView() {
		super.loadView();
	}

	public boolean shouldAutorotateToInterfaceOrientation(
			int interfaceOrientation) {
		// Allow autorotate
		return true; 
	}

	public int tableViewNumberOfRowsInSection(UITableView table, int section) {
		// The number of cells is equal to the number of data to be displayed
		return weatherData.length;
	}

	public UITableViewCell tableViewCellForRowAtIndexPath(UITableView table,
			NSIndexPath indexPath) {
		int idx = indexPath.row();
		UITableViewCell cell = new UITableViewCell();

		cell.initWithFrame(CGRect.CGRectZero());
		
		// Construct a cell with the concatenation of ui text and value text
		cell.setText(weatherData[idx].getUiText() + ": "
				+ weatherData[idx].getValueText());

		return cell;
	}

	// Inner class to contains mapping between JSON key, JSON value and UI text
	private class WeatherData {
		private String jsonName;
		private String uiText;
		private String valueText;

		public WeatherData(String jsonName, String uiName) {
			this.jsonName = jsonName;
			this.uiText = uiName;
			this.valueText = "N/A"; // Default value when not set
		}

		public void setValueText(String text) {
			valueText = text;
		}

		public String getJsonName() {
			return jsonName;
		}

		public String getUiText() {
			return uiText;
		}

		public String getValueText() {
			return valueText;
		}
	}
}
